package com.liyl.Exception;

import com.liyl.vo.Result;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;

import java.util.Objects;

/**
 * @author 80005054
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    public ResponseEntity<Result> hadleServerException(Exception exception) {
        exception.printStackTrace();
        //获取异常类型--我这只处理了500异常
        HttpStatus httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
        Class exceptionClazz = exception.getClass();
        //可以根据不同的异常类型返回不同的值
        if (Objects.equals(MissingServletRequestParameterException.class, exceptionClazz)) {
            httpStatus = HttpStatus.BAD_REQUEST;
        } else if (Objects.equals(HttpRequestMethodNotSupportedException.class, exceptionClazz)) {
            httpStatus = HttpStatus.BAD_REQUEST;
        }
        return new ResponseEntity( Result.error(), httpStatus);
    }

}